import { config } from "../config";
import { hint } from "./util";
const tips = {
    1: '服务器异常',
    404: '资源未找到'
}

class Http {
    //用对象结构赋值的方式进行传参，并且还可以给默认值
    request({ url, data = {}, method = 'GET', loading = true }) {
        return new Promise((resolve, reject) => {
            this._request(url, resolve, reject, data, method, loading)
        })
    }

    _request(url, resolve, reject, data = {}, method = 'GET', loading) {
        let token = wx.getStorageSync("token")
        console.log(token)
        let header = {
            'content-type': 'application/json' // 默认值
        }
        if (token) {
            header['X-Access-Token'] = token
        }
        if (loading) {
            wx.showLoading({
                title: '加载中',
                mask: true
            })
        }
        wx.request({
            url: config.faceUrl + url, //仅为示例，并非真实的接口地址
            data: data,
            method,
            header: header,
            success: res => {
                if (loading) {
                    wx.hideLoading()
                }
                const code = res.data.code
                if (code === 1000) {
                    resolve(res.data)
                } else {
                    this._show_error(res.data.message)
                    if (res.data.message === 'Token失效，请重新登录') {
                        wx.clearStorage({
                            success: () => {
                                wx.reLaunch({
                                    url: '/pages/login-before/index'
                                })
                            },
                            fail: () => {
                                hint("登出失败")
                            }
                        })
                    } else if (res.statusCode === 404) {
                        hint(tips[404])
                    }
                    reject(res)
                }
            },
            fail: res => {
                if (loading) {
                    wx.hideLoading()
                }
                this._show_error()
                reject(res)
            }
        })
    }

    _show_error(tip) {
        wx.showToast({
            title: tip ? tip : tips[1],
            icon: 'none',
            duration: 2000
        })
    }
}


export { Http }
